--- 模块功能：MQTT客户端数据接收处理
-- @author openLuat
-- @module mqtt.mqttInMsg
-- @license MIT
-- @copyright openLuat
-- @release 2018.03.28
module(..., package.seeall)

require "earthquakeWaringDril"
require "logGenerator"
require "utilsBySelf"
require "mqttOutMsgThird"
require "nvm"
require "thirdPartyHttpRequest"

-- 文件名
ProductName = ""
-- 参数配置文件初始化
nvm.init("config.lua", true)
-- 变量初始化
local slen, errInfo, sysTime, paramsSaveFlag = string.len, "", "", false
local mqttHost, mqttPort, groupId, clientId, uname, pwd, proTopic, drillTopic,
      ackTopic, configTopic, merchantNo, orgId, regCenter, clientNo = nvm.get(
                                                                          "thirdConfig")[1],
                                                                      nvm.get(
                                                                          "thirdConfig")[2],
                                                                      nvm.get(
                                                                          "thirdConfig")[3],
                                                                      nvm.get(
                                                                          "thirdConfig")[4],
                                                                      nvm.get(
                                                                          "thirdConfig")[5],
                                                                      nvm.get(
                                                                          "thirdConfig")[6],
                                                                      nvm.get(
                                                                          "thirdConfig")[7],
                                                                      nvm.get(
                                                                          "thirdConfig")[8],
                                                                      nvm.get(
                                                                          "thirdConfig")[9],
                                                                      nvm.get(
                                                                          "thirdConfig")[10],
                                                                      nvm.get(
                                                                          "thirdConfig")[12],
                                                                      tonumber(
                                                                          nvm.get(
                                                                              "info")[4]),
                                                                      nvm.get(
                                                                          "regCenter"),
                                                                      nvm.get(
                                                                          "info")[1]

-- 根据接收到的字符串获取msgId
local function getMsgId(getMsg)
    local msgJson, msg_id = "", ""
    msgJson = string.split(getMsg, ",")[5]
    msg_id = string.split(msgJson, ":")[2]
    return msg_id
end

--- MQTT客户端数据接收处理
-- @param mqttClient，MQTT客户端对象
-- @return 处理成功返回true，处理出错返回false
-- @usage mqttInMsg.proc(mqttClient)
function proc(mqttClient)
    local result, data, receiveMsg, optType, alertVolume, disableApp,
          disableUsb, powerLevel
    while true do
        sysTime = utilsBySelf.GetSystemTime()
        result, data = mqttClient:receive(60000, "APP_SOCKET_SEND_DATA")
        errInfo = ""
        -- 接收到数据
        if result then
            receiveMsg = data.payload
            local msgId = getMsgId(receiveMsg)
            local tjsondata, resultMqtt, errinfo = json.decode(receiveMsg)
            log.info("mqtt payload", receiveMsg, "data.topic", data.topic)
            errInfo = errInfo .. "[" .. sysTime .. "]" ..
                          "接收第三方平台消息:" .. receiveMsg ..
                          "接收主题:" .. data.topic .. "\n"
            if resultMqtt and type(tjsondata) == "table" then
                if drillTopic == data.topic then -- 第三发平台预警演练消息
                    earthquakeWaringDril.EarthquakeWarningDrillSystem(tjsondata,
                                                                      "Third",
                                                                      msgId)
                    local sendMsg = "{" .. "\"merchantNo\":\"" .. merchantNo ..
                                        "\",\"msgType\":\"2\",\"msgId\":\"" ..
                                        msgId .. "\",\"scenarioId\":\"" ..
                                        tjsondata["scenarioId"] ..
                                        "\",\"serialNumber\":\"" .. clientNo ..
                                        "\",\"receiveTime\":\"" .. sysTime ..
                                        "\",\"version\":\"" ..
                                        tjsondata["version"] .. "\"}"
                    mqttOutMsgThird.insertMsg(ackTopic, sendMsg, 0)

                elseif configTopic == data.topic then -- 第三方平台参数配置
                    if tjsondata["optType"] ~= nil and tjsondata["optType"] ~=
                        "" then
                        optType = tjsondata["optType"]
                        if optType == "1" or optType == "3" then -- 设备重启加升级
                        elseif optType == "2" then -- 恢复出厂设置
                        elseif optType == "4" then
                            if tonumber(tjsondata["adVolume"]) >= 0 and
                                tonumber(tjsondata["adVolume"]) <= 100 then
                                adVolume = tonumber(tjsondata["adVolume"])
                            end
                            if tonumber(tjsondata["alertVolume"]) >= 0 and
                                tonumber(tjsondata["alertVolume"]) <= 100 then
                                alertVolume = tonumber(tjsondata["alertVolume"])
                                nvm.set("alertVolume", alertVolume)
                                paramsSaveFlag = true
                            end
                            if tjsondata["disableApp"] == "0" or
                                tjsondata["disableApp"] == "1" then
                                if tjsondata["disableApp"] == "0" then
                                    disableApp = "false"
                                elseif tjsondata["disableApp"] == "1" then
                                    disableApp = "true"
                                end
                            end
                            if tjsondata["disableUsb"] == "0" or
                                tjsondata["disableUsb"] == "1" then
                                if tjsondata["disableUsb"] == "0" then
                                    disableUsb = "false"
                                elseif tjsondata["disableApp"] == "1" then
                                    disableUsb = "true"
                                end
                            end
                            if tjsondata["powerLevel"] == "A" or
                                tjsondata["powerLevel"] == "B" or
                                tjsondata["powerLevel"] == "C" then
                                powerLevel = tjsondata["powerLevel"]

                            end
                            if paramsSaveFlag then
                                paramsSaveFlag = false
                                sys.restart(
                                    "第三方设置参数，设备重启！")
                            end
                        end
                    else
                        sysTime = utilsBySelf.GetSystemTime()
                        errInfo = errInfo .. "[" .. sysTime .. "]" ..
                                      "操作类型为空，逻辑停止!" ..
                                      "\n"
                    end
                elseif proTopic == data.topic then
                    local scenarioId, receiveTime, version, productId
                    scenarioId = tjsondata["scenarioId"]
                    ProductName = tjsondata["productName"]
                    receiveTime = utilsBySelf.GetSystemTime()
                    productId = tjsondata["productId"]
                    version = tjsondata["version"]
                    local sendProMsg =
                        "{" .. "\"merchantNo\":\"" .. merchantNo ..
                            "\",\"msgType\":\"1\",\"msgId\":\"" .. msgId ..
                            "\",\"scenarioId\":\"" .. scenarioId ..
                            "\",\"serialNumber\":\"" .. clientNo ..
                            "\",\"receiveTime\":\"" .. receiveTime ..
                            "\",\"version\":\"" .. version .. "\"}"
                    mqttOutMsgThird.insertMsg(ackTopic, sendProMsg, 0)
                    local params = {
                        merchantNo = merchantNo,
                        serialNumber = clientNo,
                        productId = productId
                    }
                    thirdPartyHttpRequest.DownloadFillsKeson(params)
                end
            else
                sysTime = utilsBySelf.GetSystemTime()
                errInfo = errInfo .. "[" .. sysTime .. "]" ..
                              "接收第三方平台发布的消息格式错误!" ..
                              "\n"
            end
            logGenerator.generateLogTask(errInfo, "log")
        else
            break
        end
    end
    log.info("MQTT TASK RESULT", result, "MQTT TASK DATA", data)
    return result or data == "timeout" or data == "APP_SOCKET_SEND_DATA"
end
